import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { db } from '@/lib/db'
import { writeFile, mkdir } from 'fs/promises'
import path from 'path'
import { v4 as uuidv4 } from 'uuid'

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getServerSession(authOptions)
    if (!session) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 })
    }

    const { id } = await params
    const formData = await request.formData()
    
    const transitionId = formData.get('transitionId') as string
    const note = formData.get('note') as string
    const description = formData.get('description') as string
    const files = formData.getAll('files') as File[]
    
    if (!transitionId) {
      return NextResponse.json({ error: '缺少流转ID' }, { status: 400 })
    }

    // 获取项目信息
    const project = await db.project.findUnique({
      where: { id },
      include: {
        histories: true,
        resources: true
      }
    })

    if (!project) {
      return NextResponse.json({ error: '项目不存在' }, { status: 404 })
    }

    // 定义流转规则
    const flowRules: Record<string, { fromStatus: string; toStatus: string; event: string; requiresApproval: boolean }> = {
      'draft_to_review': {
        fromStatus: '草稿',
        toStatus: '待立项',
        event: '提交立项申请',
        requiresApproval: true
      },
      'review_approved': {
        fromStatus: '待立项',
        toStatus: '已立项',
        event: '审核通过',
        requiresApproval: false
      },
      'review_rejected': {
        fromStatus: '待立项',
        toStatus: '草稿',
        event: '审核不通过',
        requiresApproval: false
      },
      'assign_tasks': {
        fromStatus: '已立项',
        toStatus: '设计中',
        event: '分配任务',
        requiresApproval: false
      },
      'apply_dormancy': {
        fromStatus: '已立项',
        toStatus: '休眠',
        event: '申请休眠',
        requiresApproval: true
      },
      'design_to_development': {
        fromStatus: '设计中',
        toStatus: '开发中',
        event: '设计完成',
        requiresApproval: true
      },
      'design_dormancy': {
        fromStatus: '设计中',
        toStatus: '休眠',
        event: '申请休眠',
        requiresApproval: true
      },
      'development_to_test': {
        fromStatus: '开发中',
        toStatus: '测试中',
        event: '开发完成',
        requiresApproval: true
      },
      'development_dormancy': {
        fromStatus: '开发中',
        toStatus: '休眠',
        event: '申请休眠',
        requiresApproval: true
      },
      'test_passed': {
        fromStatus: '测试中',
        toStatus: '已完成',
        event: '测试通过',
        requiresApproval: true
      },
      'test_failed': {
        fromStatus: '测试中',
        toStatus: '开发中',
        event: '测试不通过',
        requiresApproval: false
      },
      'apply_order': {
        fromStatus: '已完成',
        toStatus: '订单准备',
        event: '申请订单',
        requiresApproval: true
      },
      'project_archive': {
        fromStatus: '已完成',
        toStatus: '已归档',
        event: '项目归档',
        requiresApproval: true
      },
      'reactivate': {
        fromStatus: '已归档',
        toStatus: '草稿',
        event: '重新激活',
        requiresApproval: true
      }
    }

    const rule = flowRules[transitionId]
    if (!rule) {
      return NextResponse.json({ error: '无效的流转操作' }, { status: 400 })
    }

    // 验证当前状态是否匹配
    if (project.statusDesc !== rule.fromStatus) {
      return NextResponse.json({ 
        error: `当前状态为${project.statusDesc}，无法执行从${rule.fromStatus}到${rule.toStatus}的流转` 
      }, { status: 400 })
    }

    // 处理文件上传
    const uploadedFiles = []
    const uploadDir = path.join(process.cwd(), 'public', 'uploads', 'projects', id)
    
    for (const file of files) {
      if (file instanceof File) {
        const bytes = await file.arrayBuffer()
        const buffer = Buffer.from(bytes)
        
        const fileExtension = path.extname(file.name)
        const fileName = `${uuidv4()}${fileExtension}`
        const filePath = path.join(uploadDir, fileName)
        
        // 确保目录存在
        await mkdir(uploadDir, { recursive: true })
        
        await writeFile(filePath, buffer)
        
        uploadedFiles.push({
          id: uuidv4(),
          name: file.name,
          type: 'attachment',
          size: file.size.toString(),
          url: `/uploads/projects/${id}/${fileName}`,
          version: '1.0'
        })
      }
    }

    // 更新项目状态
    const updatedProject = await db.project.update({
      where: { id },
      data: {
        statusDesc: rule.toStatus,
        fullStatusDesc: rule.toStatus,
        // 根据状态更新完成进度
        completionPercentage: getCompletionPercentage(rule.toStatus)
      }
    })

    // 创建流转历史记录
    const history = await db.projectHistory.create({
      data: {
        projectId: id,
        action: 'STATUS_CHANGED',
        fromLevel1: rule.fromStatus,
        toLevel1: rule.toStatus,
        description: description || note || `${rule.event}`,
        userId: session.user.id,
        createdAt: new Date()
      }
    })

    // 如果有上传的文件，创建资源记录
    if (uploadedFiles.length > 0) {
      await db.resource.createMany({
        data: uploadedFiles.map(file => ({
          projectId: id,
          ...file,
          createTime: new Date(),
          updateTime: new Date()
        }))
      })
    }

    return NextResponse.json({
      success: true,
      message: '流转操作成功',
      data: {
        project: updatedProject,
        history,
        uploadedFiles
      }
    })

  } catch (error) {
    console.error('流转操作失败:', error)
    return NextResponse.json({ error: '服务器内部错误' }, { status: 500 })
  }
}

// 根据状态计算完成进度
function getCompletionPercentage(status: string): number {
  const percentageMap: Record<string, number> = {
    '草稿': 0,
    '待立项': 5,
    '已立项': 10,
    '设计中': 25,
    '开发中': 50,
    '测试中': 75,
    '已完成': 90,
    '已归档': 100,
    '休眠': 0,
    '订单准备': 95
  }
  
  return percentageMap[status] || 0
}